package io.renren.modules.service.entity;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import io.renren.modules.service.service.UserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/app/excel")
public class ExcelController {

    @Autowired
    private UserService userService;

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<UserEntity> list = userService.list();
        String codedFileName = "测试.xls";
        Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(null, "用户表"), UserEntity.class, list);

        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(codedFileName, "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        sheets.write(out);
        out.flush();
    }
}
